<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<view class="wanl-pay">
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					<text :class="'wlIcon-'+ item.type +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view v-if="item.type == 'balance'">
							<text>可用余额 ￥{{user.money.money1}}</text>
						</view>
						<view v-else>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
			<view v-if="disabled">
				<button class="mix-btn bg-green"> <text
						class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>正在支付中... </button>
			</view>
			<view v-else>
				<button v-if="payNum == 1" class="mix-btn bg-green" @tap="confirm()"> 确认支付 </button>
				<button v-else class="mix-btn bg-green" @tap="confirm()"> 合并支付 </button>
			</view>
			<view class="footer text-center">
				<view class="text-sm wanl-gray" v-if="order_pay_no">{{orderType[order_type]}}交易号：{{order_pay_no}}</view>
				<!-- <view> © 万联支付</view> -->
			</view>
		</view>

		<uni-popup ref="popup" type="bottom">
			<view class="popup-modal">
				<view>
					<view class="auth">
						<view class="auth-title" style="padding-top: 30rpx">输入支付密码</view>
						<view class="codes">
							<view v-for="item in config.count" :key="item.key">
								<view class="input" @tap="hanldeOpenKeyboard"
									:class="{ active: currentFocus == item.index }">
									<template v-if="code[item.index - 1] != undefined">
										<!-- {{ code[item.index - 1] }} -->*
									</template>
									<template v-else>
										<view v-if="currentFocus == item.index" class="shining"></view>
									</template>
								</view>
							</view>
						</view>
					</view>
					<wanl-keyboards :open="keyboardVisible" @number="inputCode" @delete="deleteCode"
						@empty="emptyCode" />
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				token: '',
				disabled: false,
				price: '0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [],

				config: {
					count: [{
							index: 1,
							key: 'valid-code-input-1'
						},
						{
							index: 2,
							key: 'valid-code-input-2'
						},
						{
							index: 3,
							key: 'valid-code-input-3'
						},
						{
							index: 4,
							key: 'valid-code-input-4'
						},
						{
							index: 5,
							key: 'valid-code-input-5'
						},
						{
							index: 6,
							key: 'valid-code-input-6'
						}
					]
				},
				keyboardVisible: true,
				currentFocus: 1,
				code: [],
				orderType: {
					goods: '商品订单',
					groups: '团购订单',
					domestic: '家政服务订单',
					medicalvisit: '医护上门订单',
					accompany: '陪诊陪护订单',
					nursing: '医养院',
					ddcar_equipment: '医疗设备',
					card: '空间充值',
				},
				goods_type: 1,
				payMethod: '',
				payType: ''
			}
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			price(val, newval) {
				if (val <= parseFloat(this.$store.state.user.money)) {
					this.isbalance = true;
					this.getPayment();
				}
			}
		},
		async onLoad(option) {
			this.getUserInfo()
			if(option.id) {
				
				this.order_id = option.id;
			}
			if (option.goods_type && option.goods_type == 2) {
				// 积分商品
				this.goods_type = 2
			}
			if (option.type) {
				this.order_type = option.type
				// goods=商品订单 groups=团购订单 domestic=家政服务订单 medicalvisit=医护上门订单 accompany=陪诊陪护订单 nursing=医养院
				this.getOrderInfo(option)
			}
			if (option.data) {
				var sum = 0,
					data = JSON.parse(option.data),
					order_ids = [];
				console.log(data)
				if (data.length <= 1) {
					this.price = data[0].price;
					this.order_type = data[0].type;
					this.order_pay_no = data[0].pay_no;
					this.order_id = data[0].order_id;
					console.log(this.order_id, 1)
					this.getOrderInfo({
						type: data[0].type,
						id: data[0].order_id,
						len: data.length
					})
				} else {
					data.forEach(item => {
						sum = this.$wanlshop.bcadd(sum, item.price);
						order_ids.push(item.order_id);
					});
					this.price = sum;
					this.order_id = order_ids.join(',');
					this.payNum = data.length;
					console.log(this.order_id, 2)
					this.getOrderInfo({
						type: data[0].type,
						id: this.order_id,
						len: data.length
					})
				}
				this.token = option.token;
			} else {
				console.log('非法访问');
			}
		},
		methods: {
			async getUserInfo() {
				await uni.request({
					url: '/member/user/info',
					method: 'POST',
					success: res => {
						this.$store.commit('user/setUserInfo', res.data);
						this.$store.dispatch('user/setToken', res.data.token);
						this.$u.vuex('vuex_token', res.data.token);
						// 获取支付列表
						this.getPayment();
					}
				});
			},
			getOrderInfo(option) {
				uni.request({
					url: `/payment/pay/info`,
					method: 'POST',
					data: {
						order_id: option.id,
						order_type: option.type == 'homeking' ? 'homeking' : option.type
					},
					success: res => {
						this.price = res.data.order_money;
						if (option.len > 1) {
							this.order_no = '合并支付 ' + option.len + '个订单';
						} else {
							this.order_no = `订单号：${res.data.order_sn}`;
						}
						this.order_pay_no = res.data.order_sn;
						this.order_sn = res.data.order_sn;
					}
				})
			},
			inputCode(e) {
				this.code[this.currentFocus - 1] = e;
				if (this.currentFocus == 6) {
					this.wanlPay({
						pay_pass: this.code.join("").replace(/,/g, ''),
						type: this.payType,
						method: this.payMethod
					});
					this.$refs.popup.close('bottom');
					this.emptyCode()
				}
				if (this.currentFocus <= 6) {
					this.currentFocus++;
				}
			},
			deleteCode() {
				this.currentFocus--;
				this.code.splice(-1, 1);
			},
			emptyCode() {
				this.code = [];
				this.currentFocus = 0;
			},
			hanldeOpenKeyboard() {
				this.keyboardVisible = true;
			},
			getPayment() {
				let method = 'app';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
				if (this.goods_type == 1) {
					this.payList = [{
						name: '余额支付',
						describe: '',
						type: 'balance',
						method: method,
						state: true,
						select: this.isbalance ? true : false // 是否选中
					}, 
					{
						name: '支付宝',
						describe: '',
						type: 'alipay',
						method: method,
						state: true,
						select: false
					}, {
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'wechat',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					},
					];
				} else {
					this.payList = [{
						name: '积分支付',
						describe: '',
						type: 'point',
						method: method,
						state: true,
						select: true // 是否选中
					}];
				}
			},
			//确认支付
			confirm() {
				var that = this;
				let data = null;
				if (this.disabled) {
					return;
				}
				this.payList.map((value, index, array) => {
					if (value.select) {
						data = value;
					} else {
						return;
					}
				});
				
				if(!this.$store.state.user.pay_pass && data.type == "balance") {
					uni.showModal({
						title:'温馨提示',
						content: '请先设置支付密码!',
						success(res) {
							if (res.confirm) {
								that.$wanlshop.to('/pages/user/setting/security')
							}
						}
					})
					return false;
				}
				
				// 判断支付是否存在
				if (!data) {
					uni.showModal({
						content: "请选择支付方式",
						showCancel: false
					});
					return;
				} else {
					console.log(data)
					if (data.type == 'balance' || data.type == 'point') {
						this.payMethod = data.method
						this.payType = data.type
						this.$refs.popup.open('bottom');
					} else {
						this.disabled = true;
						// 获取小程序code
						// #ifdef MP
						uni.login({
							success: (e) => {
								this.wanlPay(data, e.code);
							},
							fail: (e) => {
								uni.showModal({
									content: "无法获取微信code,原因为: " + e.errMsg,
									showCancel: false
								})
							}
						})
						// #endif
						// #ifndef MP
						// 如果是公众号获取code
						this.wanlPay(data);
						// #endif
					}
				}
			},
			async wanlPay(data, code = null) {
				let order_type = this.order_type;
				let datas = await uni.request({
					url: '/publics/commons/getToken',
					method: 'POST',
					data: {
						type: `${order_type}_order_pay`
					}
				})
				await uni.request({
					url: '/payment/pay/index',
					method: 'POST',
					data: {
						pay_type: data.type,
						method: data.method,
						order_id: this.order_id,
						wxcode: code,
						pay_pass: data.pay_pass,
						order_type: order_type,
						token: datas[1].data
					},
					success: res => {
						// 余额支付/小程序支付
						switch (data.type) {
							case 'balance':
								this.$store.commit('user/setUserInfo', {
									money: this.$wanlshop.bcsub(this.$store.state.user.money, this
										.price)
								});
								this.paySuccess();
								break;
							case 'point':
								this.paySuccess();
								break;
							case 'wechat':
								// 微信 H5支付
								if (data.method == 'wap') {
									setTimeout(() => {
										uni.showModal({
											content: '请确认微信支付是否已完成',
											confirmText: '已完成',
											cancelText: '重新支付',
											success: response => {
												if (response.confirm) {
													this.paySuccess();
												} else if (response.cancel) {
													this.confirm();
												}
											}
										});
									}, 2000);
									// 异步查询是否支付成功
									window.location.href = res.data;
									// 微信 APP支付
								} else if (data.method == 'app') {
									uni.requestPayment({
										provider: 'wxpay',
										orderInfo: res.data.data,
										success: (e) => {
											console.log("success", e);
											this.paySuccess();
										},
										fail: (e) => {
											uni.showModal({
												content: "支付失败,原因为: " + e.errMsg,
												showCancel: false
											})
										},
										complete: () => {
											this.disabled = false;
										}
									})
									// 微信 小程序支付
								} else if (data.method == 'miniapp') {
									uni.requestPayment({
										appId: res.data.appId,
										nonceStr: res.data.nonceStr,
										package: res.data.package,
										paySign: res.data.paySign,
										signType: res.data.signType,
										timeStamp: res.data.timeStamp,
										success: (e) => {
											this.paySuccess();
										},
										fail: (e) => {
											uni.showModal({
												content: "支付失败,原因为: " + e.errMsg,
												showCancel: false
											})
										}
									})
									// 微信 公众平台支付
								} else if (data.method == 'mp') {
									this.$jssdk.wxpay({
										data: res.data,
										success: e => {
											this.paySuccess();
										},
										fail: err => {
											if (err.errMsg == "chooseWXPay:ok") {
												this.$wanlshop.msg('支付成功');
											} else if (err.errMsg == "chooseWXPay:cancel") {
												this.$wanlshop.msg('支付失败，取消支付');
											} else if (err.errMsg == "chooseWXPay:fail") {
												this.$wanlshop.msg('支付失败');
											}
										}
									})
								}
								break;
							case 'alipay':
								if (data.method == 'wap') {
									this.disabled = false;
									if (this.order_type === 'goods') {
										this.$store.commit('statistics/order', {
											pay: this.$wanlshop.bcsub(this.$store.state.statistics
												.order.pay, this.payNum),
											delive: this.$wanlshop.bcadd(this.$store.state
												.statistics.order.delive, this.payNum)
										});
									}
									document.write(res.data);
								} else if (data.method == 'app') {
									uni.requestPayment({
										provider: 'alipay',
										orderInfo: res.data.data,
										success: (e) => {
											console.log("success", e);
											this.paySuccess();
										},
										fail: (e) => {
											this.$wanlshop.msg(JSON.stringify(e))
										},
										complete: (e) => {
											this.disabled = false;
										}
									})
								}
								break;
						}
					},
					fail: () => {
						this.disabled = false;
					}
				});
			},
			onSelect(key) {
				this.payList.map((value, index, array) => {
					if (index == key) {
						value.select = !value.select;
					} else {
						value.select = false;
					}
				});
			},
			// 支付成功
			paySuccess() {
				this.disabled = false;
				if (this.order_type === 'goods') {
					this.$store.commit('statistics/order', {
						pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
						delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
					});
				}
				if (this.order_type == 'ddcar_equipment') {
					uni.redirectTo({
						url: `/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`
					})
				} else {
					this.$wanlshop.to(
						`/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`);
				}

			}
		}
	}
</script>

<style>
	@import url("@/pages/user/auth/auth.css");

	/deep/.fade-out.uni-transition {
		background: rgba(0, 0, 0, .4) !important;
	}

	.popup-modal {
		background-color: #fff;
		height: 900rpx;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;

	}

	page {
		background-color: white;
	}

	radio-group {
		display: block;
	}
</style>